package cn.hp.config;

import javax.activation.DataSource;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;

import lombok.Data;
@Data
@Configuration
@ConditionalOnClass(value= {DataSource.class,DruidDataSource.class})
@ConfigurationProperties(prefix="spring.datasource.druid.web")
public class MyDruidDataSource {
	//松散绑定：变量名称是由两个英文单词组成的
	private String loginUsername = "admin";
	private String loginPassword = "123456";
	private String allow = "";
	private String deny = "";
	private String urlMappings = "/druid/*";

	@Bean(initMethod="init")
	//被动的接收IOC容器中的值
	@ConfigurationProperties(prefix="spring.datasource.druid")
	public DruidDataSource druidDataSource() {
		
		DruidDataSource druidDataSource = new  DruidDataSource();
		System.out.println(druidDataSource.hashCode());
		
		//最大连接池的数量
		//druidDataSource.setMaxActive(maxActive);
		//初始化时建立物理连接的个数
		//druidDataSource.setMaxWait(maxWaitMillis);
		//获取连接时最大等待时间，单位毫秒
		//druidDataSource.setInitialSize(initialSize);
		//属性类型是字符串，通过别名的方式配置扩展插件，
		//常用的插件有:监控统计用的 filter:stat日志用的filter:log4j防御sql注入的filter:wall
		//druidDataSource.setFilters(filters);
		
		return druidDataSource;
	}
	
	//创建StatViewServlet
	@Bean(name="druid")
	public StatViewServlet statViewServlet() {
		return new StatViewServlet();
	}
	
	//注册StatViewServlet
	@Bean
	public ServletRegistrationBean<StatViewServlet> servletRegistrationBeanStatViewServlet(StatViewServlet statViewServlet){
		ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>();
		registrationBean.setServlet(statViewServlet);
		//设置登录用户名
		registrationBean.addInitParameter("loginUsername", loginUsername);
		//设置登录密码
		registrationBean.addInitParameter("loginPassword", loginPassword);
		//设置白名单
		registrationBean.addInitParameter("allow", allow);
		//设置黑名单
		registrationBean.addInitParameter("deny", deny);
		
		//设置映射
		registrationBean.addUrlMappings(urlMappings);
		
		return registrationBean;
	} 
}
